/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snda.lidejia.xml2pojo;

import com.snda.lidejia.xml2pojo.exception.XMLParserException;
import com.snda.lidejia.xml2pojo.parser.XMLParser;
import com.snda.lidejia.xml2pojo.parser.XMLParserPool;
import java.io.InputStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author lidejia
 */
public class XMLMapping {

    private static final Logger LOGGER = LoggerFactory.getLogger(XMLMapping.class);

    public static <T> T mapping(Class<T> type, InputStream stream) throws XMLParserException {
        T instance = null;
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(stream);
            XMLParser parser = XMLParserPool.getInstance().getParser(Object.class);
            instance = (T) parser.parse(type, document.getRootElement());
        } catch (DocumentException ex) {
            LOGGER.error("reading xml error", ex);
            throw new XMLParserException(ex);
        }
        return instance;
    }
}
